package com.wk.springboot.util;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @Classname FileUtil
 * @Description TODO
 * @Date 2019/12/3 15:47
 * @Author by weikai
 */
public class FileUtil {

  /**
   * The number of bytes in a kilobyte.
   */
  public static final long ONE_KB = 1024;

  public static final long ONE_MB = ONE_KB * ONE_KB;

  private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30;

  public static void copyFile(final File srcFile, final File destFile, FileChannel input,FileChannel output,final boolean preserveFileDate)
      throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
      throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    try {
      final long size = input.size(); // TODO See IO-386
      long pos = 0;
      long count = 0;
      int i = 0;
      while (pos < size) {
        if(i==100){
          System.out.println("已经循环了100次，累了，睡一会儿");
          Thread.sleep(45000);
          System.out.println("睡醒了，继续吧==========");
        }
        final long remain = size - pos;
        count = remain > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : remain;
        final long bytesCopied = output.transferFrom(input, pos, count);
        if (bytesCopied == 0) { // IO-385 - can happen if file is truncated after caching the size
          break; // ensure we don't loop forever
        }
        pos += bytesCopied;
        i++;
      }
    }catch (Exception e){

    }

    final long srcLen = srcFile.length(); // TODO See IO-386
    final long dstLen = destFile.length(); // TODO See IO-386
    if (srcLen != dstLen) {
      throw new IOException("Failed to copy full contents from '" +
          srcFile + "' to '" + destFile + "' Expected length: " + srcLen + " Actual: " + dstLen);
    }
    if (preserveFileDate) {
      destFile.setLastModified(srcFile.lastModified());
    }
  }

}
